/**
 * Created with IntelliJ IDEA.
 * User: osereda
 * Date: 31.05.13
 */
package com.google.code.bankagregator.common;

import com.google.code.bankagregator.adapter.exception.AdapterConnectException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

/**
 * Connect with preset connection parameters.
 */
public class SiteConnect {

    private final String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;)";
    private final int MAX_HTML_PAGE_SIZE = 1024 * 1024;
    private final int TIMEOUT = 8000;
    private Connection connection;

    /**
     * Create Jsoup connection to target URL
     *
     * @param url target URL
     * @throws com.google.code.bankagregator.adapter.exception.AdapterConnectException
     *          then connection fail.
     */
    public SiteConnect(final String url) {
        connection = Jsoup.connect(url).
                userAgent(USER_AGENT).
                maxBodySize(MAX_HTML_PAGE_SIZE).
                timeout(TIMEOUT);
    }

    /**
     * @return specified by constructor Jsoup.Connection
     */
    public Connection getConnection() {
        return connection;
    }

    /**
     * Getter for Jsoup.Document related to specified URL
     *
     * @return Jsoup.Document
     */
    public Document getPage() throws AdapterConnectException {
        try {
            return getConnection().get();
        } catch (IOException e) {
            throw new AdapterConnectException(e.getMessage());
        }
    }
}
